<template>
  <div>
    <el-form ref="addForm" :model="form" label-width="80px" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input :disabled='isEdit' v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="departmentId">
            <el-select
              clearable
              v-model="form.departmentId"
              placeholder="请选择所属部门"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio :label="1">帅哥</el-radio>
              <el-radio :label="0">美女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input
          type="password"
          v-model="form.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phoneNumber">
        <el-input v-model="form.phoneNumber" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="生日" prop="birth">
        <el-date-picker
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy年MM月dd日"
          v-model="form.birth"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex; justify-content: flex-end">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSumbit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { getDeptListApi } from '../../../api/department'
import { AddUserApi, getUserApi, EditUserApi } from '../../../api/user'
export default {
  props: ['isEdit', 'id'],
  data () {
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      form: {
        username: '',
        departmentId: null,
        phoneNumber: '',
        password: '',
        email: '',
        nickname: '',
        sex: '',
        birth: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: 'blur'
          }
        ],
        departmentId: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        birth: [{ required: true, message: '请填写出生日期', trigger: 'blur' }],
        email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
        phoneNumber: [
          {
            required: true,
            message: '请输入联系方式',
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          {
            min: 5,
            max: 10,
            message: '长度在 5 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      options: []
    }
  },
  methods: {
    // 获取部门
    async getDeps () {
      const res = await getDeptListApi()
      if (!res.success) return this.$message.error('获取失败')
      this.options = res.data
    },
    // 关闭弹窗
    handleClose () {
      this.$emit('close')
    },
    // 提交事件
    handleSumbit () {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.onEdit() : this.onAdd()
      })
    },
    // 做添加
    async onAdd () {
      this.form.sex = Number(this.form.sex)
      const res = await AddUserApi(this.form)
      if (!res.success) {
        this.$notify({
          title: '失败',
          message: '新增用户失败',
          type: 'error'
        })
        this.handleClose()
        return
      }
      this.handleClose()
      this.$emit('getUserList')
      this.$notify({
        title: '成功',
        message: '新增用户成功',
        type: 'success'
      })
    },
    // 做编辑
    async onEdit () {
      const res = await EditUserApi(this.id, this.form)
      if (!res.success) {
        this.$notify({
          title: '失败',
          message: '更新用户失败',
          type: 'error'
        })
        this.handleClose()
        return
      }
      this.handleClose()
      this.$emit('getUserList')
      this.$notify({
        title: '成功',
        message: '更新用户成功',
        type: 'success'
      })
    },
    // 获取用户信息
    async getUser () {
      const res = await getUserApi(this.id)
      if (!res.success) return this.$notify.error('获取用户信息失败')
      this.form = res.data
    }
  },
  created () {
    this.getDeps()
    if (this.isEdit) {
      this.getUser()
    }
  }
}
</script>

<style lang='less' scoped>
.ft {
}
</style>
